<template>
  <div class="app-container">
    <!-- 数据概览卡片 -->
    <div class="data-overview">
      <div class="overview-card entrance">
        <div class="card-title">入口车道</div>
        <div class="card-value">{{ entranceCount }}</div>
      </div>
      <div class="overview-card exit">
        <div class="card-title">出口车道</div>
        <div class="card-value">{{ exitCount }}</div>
      </div>
      <div class="overview-card active">
        <div class="card-title">已启用</div>
        <div class="card-value">{{ activeCount }}</div>
      </div>
      <div class="overview-card inactive">
        <div class="card-title">未启用</div>
        <div class="card-value">{{ inactiveCount }}</div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="车道名称" prop="laneName">
          <el-input v-model="queryParams.laneName" placeholder="请输入车道名称" clearable />
        </el-form-item>
        <el-form-item label="车道类型" prop="laneType">
          <el-select v-model="queryParams.laneType" placeholder="请选择车道类型" clearable>
            <el-option label="入口" value="1" />
            <el-option label="出口" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增车道</el-button>
      <el-button type="success" icon="el-icon-download">导出数据</el-button>
    </div>

    <!-- 修改表格和分页的样式 -->
    <div class="table-wrapper">
      <el-table 
        v-loading="loading" 
        :data="laneList"
        class="custom-table">
        <el-table-column label="车道名称" prop="laneName" />
        <el-table-column label="车道类型" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.laneType === '1' ? 'success' : 'warning'">
              {{ scope.row.laneType === '1' ? '入口' : '出口' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属停车场" align="center" prop="lotName">
          <template slot-scope="scope">
            <span>{{ getLotName(scope.row.lotId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center" width="120">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.qrCode"
              :src="scope.row.qrCode"
              :preview-src-list="[scope.row.qrCode]"
              fit="contain"
              style="width: 50px; height: 50px"
            >
              <div slot="error">
                <el-button 
                  type="text"
                  @click="handleGenerateQR(scope.row)"
                >
                  生成二维码
                </el-button>
              </div>
            </el-image>
            <el-button 
              v-else
              type="text"
              @click="handleGenerateQR(scope.row)"
            >
              生成二维码
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          :current-page.sync="queryParams.pageNum"
          :page-size.sync="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/修改车道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="车道名称" prop="laneName">
          <el-input v-model="form.laneName" placeholder="请输入车道名称" />
        </el-form-item>
        <el-form-item label="车道类型" prop="laneType">
          <el-select v-model="form.laneType" placeholder="请选择车道类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属停车场" prop="lotId">
          <el-select v-model="form.lotId" placeholder="请选择停车场">
            <el-option
              v-for="lot in lotOptions"
              :key="lot.lotId"
              :label="lot.lotName"
              :value="lot.lotId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLane, getLane, addLane, updateLane, deleteLane, generateQrCode } from '@/api/parking/lane.js'
import { parkingApi } from '@/api/parking.js'
import { MessageBox, Message } from 'element-ui'

export default {
  name: "ParkingLaneList",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      laneList: [],
      typeOptions: [
        { dictLabel: '入口', dictValue: '1' },
        { dictLabel: '出口', dictValue: '2' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        laneName: undefined,
        laneType: undefined,
        lotId: undefined
      },
      form: {
        laneId: undefined,
        laneName: undefined,
        laneType: undefined,
        lotId: undefined,
        qrCode: undefined
      },
      rules: {
        laneName: [
          { required: true, message: "车道名称不能为空", trigger: "blur" }
        ],
        laneType: [
          { required: true, message: "车道类型不能为空", trigger: "change" }
        ],
        lotId: [
          { required: true, message: "所属停车场不能为空", trigger: "change" }
        ]
      },
      lotOptions: [],
      lotNameMap: {},
      title: "",
      open: false,
      entranceCount: 0,
      exitCount: 0,
      activeCount: 0,
      inactiveCount: 0
    };
  },
  created() {
    try {
      console.log('组件创建，开始获取数据');
      this.getList();
      this.getLotOptions();
    } catch (error) {
      console.error('初始化失败:', error);
      this.$message.error('页面初始化失败');
    }
  },
  computed: {
    // 在这里定义计算属性
  },
  methods: {
    getList() {
      this.loading = true;
      console.log('发起请求参数:', this.queryParams); // 添加日志
      listLane(this.queryParams).then(response => {
        console.log('API响应数据:', response); // 添加日志
        if (response.code === 200) {
          const { total, rows } = response.data;
          this.laneList = rows;
          this.total = total;
          console.log('处理后的列表数据:', this.laneList); // 添加日志
          this.entranceCount = this.laneList.filter(lane => lane.laneType === '1').length;
          this.exitCount = this.laneList.filter(lane => lane.laneType === '2').length;
          this.activeCount = this.laneList.filter(lane => lane.status === '0').length;
          this.inactiveCount = this.laneList.filter(lane => lane.status === '1').length;
        } else {
          this.$message.error(response.msg || '获取数据失败');
        }
        this.loading = false;
      }).catch((error) => {
        console.error('API请求失败:', error); // 添加错误日志
        this.$message.error('获取车道列表失败');
        this.loading = false;
      });
    },
    handlePaginationChange() {
      this.getList(); // 直接重新请求数据
    },
    handleQuery() {
      console.log('执行查询，参数:', this.queryParams);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      console.log('执行重置');
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车道";
    },
    handleUpdate(row) {
      this.reset();
      const laneId = row.laneId;
      getLane(laneId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车道";
      });
    },
    handleDelete(row) {
      const laneId = row.laneId;
      MessageBox.confirm(
        `是否确认删除车道编号为"${laneId}"的数据项？`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        return deleteLane(laneId);
      }).then(() => {
        this.getList();
        Message.success("删除成功");
      }).catch((err) => {
        if (err !== 'cancel') {
          Message.error("删除失败");
        }
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            laneType: this.form.laneType.toString()
          };
          
          if (this.form.laneId) {
            updateLane(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addLane(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handleGenerateQR(row) {
      this.$confirm('确认要生成二维码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        generateQrCode(row.laneId).then(response => {
          if (response.code === 200) {
            // 更新本地数据
            row.qrCode = response.data
            this.$message.success('二维码生成成功')
            this.getList();
            
            // 打印二维码内容以便调试
            try {
              const qrData = response.data.split(',')[1] // 获取base64数据部分
              const decodedData = atob(qrData) // 解码base64
              console.log('二维码内容:', decodedData)
            } catch (error) {
              console.error('二维码内容解析失败:', error)
            }
          } else {
            this.$message.error(response.msg || '二维码生成失败')
          }
        }).catch(error => {
          console.error('生成二维码失败:', error)
          this.$message.error('二维码生成失败')
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message.info('已取消生成')
      })
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        laneId: undefined,
        laneName: undefined,
        laneType: undefined,
        lotId: undefined,
        qrCode: undefined
      };
      this.resetForm("form");
    },
    getLaneTypeLabel(value) {
      const option = this.typeOptions.find(opt => opt.dictValue === value);
      return option ? option.dictLabel : '';
    },
    resetData() {
      this.laneList = [];
      this.total = 0;
    },
    getLotOptions() {
      parkingApi.getParkingLotList().then(response => {
        if (response.code === 200) {
          this.lotOptions = response.data.rows.map(lot => ({
            lotId: lot.lotId,
            lotName: lot.lotName
          }));
          this.lotNameMap = this.lotOptions.reduce((acc, lot) => {
            acc[lot.lotId] = lot.lotName;
            return acc;
          }, {});
        } else {
          this.$message.error(response.msg || '获取停车场列表失败');
        }
      }).catch(error => {
        console.error('获取停车场列表失败:', error);
        this.$message.error('获取停车场列表失败');
      });
    },
    getLotName(lotId) {
      return this.lotNameMap[lotId] || '未知停车场';
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f0f2f5;

  // 数据概览卡片样式
  .data-overview {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;

    .overview-card {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
      }

      .card-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #2d8cf0;
      }

      &.entrance {
        .card-value {
          color: #2d8cf0; // 蓝色
        }
      }

      &.exit {
        .card-value {
          color: #f56c6c; // 红色
        }
      }

      &.active {
        .card-value {
          color: #67c23a; // 绿色
        }
      }

      &.inactive {
        .card-value {
          color: #909399; // 灰色
        }
      }
    }
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .data-overview {
      flex-direction: column;
      
      .overview-card {
        width: 100%;
      }
    }
  }

  // 搜索表单样式优化
  .el-form {
    background: rgba(255, 255, 255, 0.95);
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.8);

    .el-form-item {
      margin-bottom: 16px;
      
      .el-input__inner,
      .el-select .el-input__inner {
        border-radius: 8px;
        border: 1px solid #e4e7ed;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #2d8cf0;
          box-shadow: 0 0 0 2px rgba(45, 140, 240, 0.1);
        }
        
        &:focus {
          border-color: #2d8cf0;
          box-shadow: 0 0 0 3px rgba(45, 140, 240, 0.15);
        }
      }
    }
  }

  // 按钮组样式优化
  .mb8 {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;

    .el-button {
      padding: 10px 20px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &.el-button--primary {
        background: linear-gradient(135deg, #3498db, #2980b9);
        border: none;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(45, 140, 240, 0.35);
          background: linear-gradient(135deg, #3498db, #2573a7);
        }
      }

      &:not(.el-button--primary) {
        background: white;
        border: 1px solid #dcdfe6;
        
        &:hover {
          border-color: #2d8cf0;
          color: #2d8cf0;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  // 表格样式优化
  .el-table {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    background: white;
    border: 1px solid rgba(255, 255, 255, 0.8);

    &::before {
      display: none;
    }

    .el-table__header-wrapper {
      th {
        background: #f8f9fb;
        color: #1f2d3d;
        font-weight: 600;
      }
    }

    .el-table__row {
      td {
        padding: 12px 0;
      }
    }

    .el-button--text {
      padding: 0 8px;
      font-size: 13px;
      &:hover {
        color: #2d8cf0;
      }
    }

    .el-image {
      border-radius: 4px;
      transition: transform 0.3s;
      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .el-dialog {
    border-radius: 8px;
    overflow: hidden;

    .el-dialog__header {
      background: #f8f9fb;
      padding: 15px 20px;
      margin: 0;
      border-bottom: 1px solid #ebeef5;

      .el-dialog__title {
        font-size: 16px;
        font-weight: 600;
        color: #1f2d3d;
      }
    }

    .el-dialog__body {
      padding: 30px;
    }

    .el-dialog__footer {
      border-top: 1px solid #ebeef5;
      padding: 15px 20px;
    }

    .el-form-item {
      margin-bottom: 22px;

      .el-input,
      .el-select {
        width: 100%;
      }
    }

    .dialog-footer {
      text-align: right;
      
      .el-button {
        padding: 9px 20px;
        
        &.el-button--primary {
          background: #2b85e4;
          &:hover {
            background: #2d8cf0;
          }
        }
      }
    }
  }

  .pagination-container {
    padding: 15px;
    text-align: right;
    background: #fff;
    .el-pagination {
      padding: 0;
      margin: 0;
    }
  }

  // 美化表单控件
  .el-input,
  .el-select {
    .el-input__inner {
      border-radius: 4px;
      &:hover {
        border-color: #2d8cf0;
      }
      &:focus {
        border-color: #2d8cf0;
      }
    }
  }

  // 按钮样式优化
  .el-button {
    border-radius: 4px;
    transition: all 0.3s;
    
    &.el-button--primary {
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(45, 140, 240, 0.3);
      }
    }
  }

  // 搜索区域样式
  .search-box {
    .el-form-item {
      margin-bottom: 0;
      margin-right: 15px;
    }
  }

  // 修改表格和分页的样式
  .table-wrapper {
    background: #fff;
    border-radius: 4px;
    
    .custom-table {
      margin-bottom: 0;
    }
  }
}

.el-image {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.el-image-viewer__wrapper {
  .el-image-viewer__btn {
    color: #fff;
    
    i {
      font-size: 24px;
    }
  }
}
</style> 